//
//  RulePredicateEditor.m
//  Pennyworth
//
//  Created by Chris Karr on 7/28/08.
//  Copyright 2008 Northwestern University. All rights reserved.
//

#import "RulePredicateEditor.h"
#import "C45Learner.h"
#import "RulesRowTemplate.h"

@implementation RulePredicateEditor

- (RulePredicateEditor *) init
{
	if (self = [super init])
		loaded = NO;
	
	return self;
}

- (void) setRowTemplates:(NSArray *) templates
{
	NSArray * examples = ((DecisionTreeLearner *) user.learner).examples;
	
	NSMutableSet * sensors = [NSMutableSet set];

	if (examples != nil)
	{
		for (NSDictionary * example in examples)
		{
			for (NSString * name in [example allKeys])
			{
				name = [name stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@" %@", NUMERIC]
													   withString:@""];
				
				NSRange range = [name rangeOfString:@" :: " options:0 range:NSMakeRange(0, [name length])];
				
				if (range.location != NSNotFound)
					name = [name substringToIndex:range.location];
				
				[sensors addObject:name];
			}
		}
		
		[sensors removeObject:LABEL_KEY];
		
		loaded = YES;
	}
	else
	{
		[sensors addObject:@"Loading..."];
		[sensors addObject:@"Loading..."];
	}
	
	NSMutableArray * ruleTemplates = [NSMutableArray arrayWithArray:templates];
	
	NSArray * sensorNames = [[sensors allObjects] sortedArrayUsingSelector:@selector(compare:)];
	
	NSPredicateEditorRowTemplate * original = [ruleTemplates lastObject];
	
	NSMutableArray * lefts = [NSMutableArray array];
	
	for (NSString * item in sensorNames)
	{
		NSExpression * keyPath = [NSExpression expressionForKeyPath:item];
		[lefts addObject:keyPath];
	}
	
	NSArray * operators = [NSArray arrayWithObjects:[NSNumber numberWithInteger:NSEqualToPredicateOperatorType],
						   [NSNumber numberWithInteger:NSNotEqualToPredicateOperatorType],
						   [NSNumber numberWithInteger:NSContainsPredicateOperatorType],
						   [NSNumber numberWithInteger:NSLessThanOrEqualToPredicateOperatorType],
						   [NSNumber numberWithInteger:NSGreaterThanOrEqualToPredicateOperatorType],
						   [NSNumber numberWithInteger:NSMatchesPredicateOperatorType],
						   [NSNumber numberWithInteger:NSLikePredicateOperatorType], nil];
	
	RulesRowTemplate * template = [[RulesRowTemplate alloc] initWithLeftExpressions:lefts
													   rightExpressionAttributeType:NSStringAttributeType
																		   modifier:[original modifier]
																		  operators:operators
																			options:[original options]];
	
	[ruleTemplates removeLastObject];
	[ruleTemplates addObject:template];
	
	[super setRowTemplates:ruleTemplates];
	
	if (loaded)
		[self reloadCriteria];
}

- (void) setObjectValue:(NSPredicate *) predicate
{
	if (!loaded)
		[self setRowTemplates:[self rowTemplates]];

	[super setObjectValue:predicate];
}

@end
